import { resolve } from 'path'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import LegacyPlugin from '@vitejs/plugin-legacy';
import autoprefixer from 'autoprefixer';

export default defineConfig(({ mode }) => {
  // js兼容性处理
  const jsplugin = mode == 'production' ? LegacyPlugin({
    targets: ["chrome < 60", "edge < 15"],
    additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
    renderLegacyChunks: true
  }) : [];
  // css兼容性出来
  const cssplugin = mode == 'production' ? [
    autoprefixer({
      overrideBrowserslist: ['last 2 versions'],
      grid: true,
      flexbox: true
    })
  ] : [];

  return {
    root: './src/',
    base: './',
    publicDir: './src/assets/',
    plugins: [react()].concat(jsplugin),
    server: {
      open: true,
      port: 2024
    },
    resolve: {
      extensions: ['.js', '.jsx', '.scss']
    },
    css: {
      devSourcemap: true,
      postcss: {
        plugins: cssplugin
      }
    },
    build: {
      outDir: resolve(__dirname, './build'),
      emptyOutDir: true,
      sourcemap: true,
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: asset => {
            if (asset.name.includes('.css')) {
              return 'style/[name]-[hash].css';
            } else {
              return 'assets/[name].[ext]';
            }
          },
          manualChunks: {
            'vendor': ['react', 'react-dom']
          }
        }
      }
    }
  }
})
